﻿using System;
using System.Linq;
using NJabber.Stream.Elements;

namespace NJabber.Client
{
    public class IqStanzaHandler : IStanzaHandler<IqStanza>
    {
        private IRosterCache rosterCache;

        public IqStanzaHandler(IRosterCache rosterCache)
        {
            if (rosterCache == null) throw new ArgumentNullException("rosterCache");
            this.rosterCache = rosterCache;
        }

        public bool ProcessStanza(XmppClientRuntime context, IqStanza stanza)
        {
            if (stanza == null) throw new ArgumentNullException("stanza");
            if (stanza.IsRosterResult()) ProcessRosterResult(stanza);
            if (IsRosterPush(stanza)) ProcessItemPush(stanza);

            return true;
        }

        private void ProcessRosterResult(IqStanza stanza)
        {
            var rosterItems = stanza.GetRosterItemsElements().Select(ri => (RosterItem) ri);
            rosterCache.Reset(rosterItems);
        }

        private static bool IsRosterPush(IqStanza stanza)
        {
            return stanza.Type == IqStanzaTypes.Set && stanza.HasRosterQuery();
        }

        private void ProcessItemPush(IqStanza stanza)
        {
            RosterItem rosterItem = stanza.GetRosterItemsElements().Single();
            rosterCache.Push(rosterItem);
        }
    }
}
